import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, convertFromHTML, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { packageConfigList, packageConfigAdd, packageConfigUpdate } from '../../services/api';
import { getArrFromObj } from '../../utils/utils';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './packageConfig.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const GRANT_WAY_MAP = {
  '0': '手工发放',
  '1': '自动发放',
};

const GRANT_WAY_ARR = getArrFromObj(GRANT_WAY_MAP);

const PAGE_SIZE = 10;

@connect(({ packageConfig, loading }) => {
  return {
    packageConfig,
    loading: loading.models.packageConfig,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    id: null,
    levelRule: '',
    name: '',
  };

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'packageConfig/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'packageConfig/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'packageConfig/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime) {
        fieldsValue.startTime =
          moment(fieldsValue.createTime[0]).format('YYYY-MM-DD') + 'T00:00:00Z';
        fieldsValue.endTime = moment(fieldsValue.createTime[1]).format('YYYY-MM-DD') + 'T23:59:59Z';
      }

      delete fieldsValue['createTime'];

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      dispatch({
        type: 'packageConfig/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      levelRule: '',
      name: '',
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const { value, name } = this.state;
    if (!name) {
      return message.error('请填写套餐名称');
    }

    if (!value) {
      return message.error('请填写可监控专利数');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, name, value } = this.state;

    let response = {};
    if (id) {
      const params = { id, name, value };
      response = await packageConfigUpdate(params);
    } else {
      const params = { name, value };
      response = await packageConfigAdd(params);
    }

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      this.init();
    } else {
      message.error(response.message);
    }
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleEdit(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleShowModal.bind(this)}>
                新增套餐
              </Button>
            </span>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
        </Row>
      </Form>
    );
  }

  render() {
    let { packageConfig: { data }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '套餐名称',
        ellipsis: true,
        width: 100,
        dataIndex: 'name',
      },
      {
        title: '套餐内容',
        dataIndex: 'value',
        render: val => <span>可监控专利数：{val || '-'} 件</span>,
      },
      {
        title: '获取方式',
        dataIndex: 'grantWay',
        render: val => <span>{GRANT_WAY_MAP[val] || '-'}</span>,
      },
      {
        title: '添加人',
        dataIndex: 'createUser',
        render: val => <span>{val || '-'}</span>,
      },
      {
        title: '添加时间',
        dataIndex: 'createTime',
        render: val => <span>{val ? moment(val).format('YYYY-MM-DD') : '-'}</span>,
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="套餐配置">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          style={{ width: '800px' }}
          title={!this.state.id ? '新增套餐' : '编辑套餐'}
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" title="" col="1">
            <Description term="套餐名称">
              <Input value={this.state.name} onChange={this.handleOnchange.bind(this, 'name')} />
            </Description>
            <Description term="套餐内容">
              可监控专利数<Input
                style={{ width: 100 }}
                value={this.state.value}
                onChange={this.handleOnchange.bind(this, 'value')}
              />件。
            </Description>
          </DescriptionList>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
